package evs.client;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class VirtualIPFilter implements javax.servlet.Filter {
	
	public VirtualIPFilter() {

	}

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

	    ServletRequest realRequest = request;
	    
	    if ( request instanceof HttpServletRequest )
	    {
	        HttpServletRequest httpRequest = (HttpServletRequest) request;
	        
	        String virtualIP = httpRequest.getHeader( "x-virtual-ip" );
	        
	        if ( virtualIP != null )
	        {
	            VirtualIPRequestWrapper wrapper = new VirtualIPRequestWrapper( httpRequest );
	            wrapper.setRemoteAddr( virtualIP );
	            
	            realRequest = wrapper;
	        }
	    }
	    
	    chain.doFilter( realRequest, response );
	}

    @Override
    public void init( FilterConfig arg0 ) throws ServletException
    {
        
    }
}
